"""
添加有图片且热度高的景点
"""
import time
from django.core.management.base import BaseCommand
from django.conf import settings
from apps.attractions.models import Attraction
from utils.amap_client import AMapClient


class Command(BaseCommand):
    help = '添加有图片且热度高的景点'

    def add_arguments(self, parser):
        parser.add_argument(
            '--location',
            type=str,
            default='115.858197,28.682892',  # 南昌市中心坐标
            help='中心点坐标，格式："经度,纬度"'
        )
        parser.add_argument(
            '--radius',
            type=int,
            default=20000,  # 扩大搜索半径
            help='搜索半径（米）'
        )
        parser.add_argument(
            '--max-count',
            type=int,
            default=20,
            help='最多添加多少个景点'
        )
        parser.add_argument(
            '--skip-existing',
            action='store_true',
            help='跳过已存在的景点'
        )

    def handle(self, *args, **options):
        self.stdout.write('开始添加热门景点...')

        api_key = settings.AMAP_CONFIG.get('API_KEY')
        if not api_key:
            self.stdout.write(self.style.ERROR('没有API Key'))
            return

        amap_client = AMapClient(api_key)
        location = options['location']
        radius = options['radius']
        max_count = options['max_count']
        skip_existing = options['skip_existing']

        self.stdout.write(f'搜索位置: {location}')
        self.stdout.write(f'搜索半径: {radius}米')
        self.stdout.write(f'最多添加: {max_count}个景点')

        # 搜索热门景点
        added_count = 0
        page = 1
        page_size = 20

        while added_count < max_count:
            try:
                # 搜索景点（按热度排序）
                result = amap_client.search_pois_by_location(
                    location=location,
                    types='风景名胜|公园广场|博物馆|展览馆|历史遗迹',
                    radius=radius,
                    page=page,
                    page_size=min(page_size, max_count - added_count)
                )

                if result.get('status') != '1':
                    self.stdout.write(self.style.ERROR(f'搜索失败: {result.get("info", "未知错误")}'))
                    break

                pois = result.get('pois', [])
                if not pois:
                    self.stdout.write('没有更多景点了')
                    break

                self.stdout.write(f'第{page}页找到 {len(pois)} 个景点')

                for poi in pois:
                    if added_count >= max_count:
                        break

                    poi_id = poi.get('id')
                    name = poi.get('name', '')

                    # 跳过已存在的景点
                    if skip_existing and Attraction.objects.filter(amap_poi_id=poi_id).exists():
                        self.stdout.write(f'跳过已存在的景点: {name}')
                        continue

                    # 检查是否有图片
                    photos = poi.get('photos', [])
                    if not photos:
                        self.stdout.write(f'跳过没有图片的景点: {name}')
                        continue

                    # 提取图片URL
                    image_urls = []
                    for photo in photos[:5]:  # 最多5张
                        if isinstance(photo, dict):
                            url = photo.get('url', '') or photo.get('src', '')
                            if url:
                                if not url.startswith('http'):
                                    if url.startswith('//'):
                                        url = 'https:' + url
                                    elif url.startswith('/'):
                                        url = 'https://restapi.amap.com' + url
                                    else:
                                        continue
                                if url.startswith('http'):
                                    image_urls.append(url)

                    if not image_urls:
                        self.stdout.write(f'跳过没有有效图片的景点: {name}')
                        continue

                    # 提取其他信息
                    address = poi.get('address', '')
                    tel = poi.get('tel', '')
                    tag = poi.get('tag', '')
                    website = poi.get('website', '')

                    # 解析坐标
                    location_str = poi.get('location', '')
                    lat, lng = None, None
                    if location_str and ',' in location_str:
                        try:
                            lng, lat = location_str.split(',')
                            lat, lng = float(lat), float(lng)
                        except (ValueError, TypeError):
                            pass

                    # 解析评分
                    try:
                        rating = float(poi.get('biz_ext', {}).get('rating', '0'))
                    except (ValueError, TypeError):
                        rating = 0.0

                    # 创建或更新景点
                    attraction, created = Attraction.objects.update_or_create(
                        amap_poi_id=poi_id,
                        defaults={
                            'name': name,
                            'description': f"{tag}\n{address}".strip() if tag else address,
                            'address': address,
                            'latitude': lat,
                            'longitude': lng,
                            'rating': rating,
                            'amap_image_urls': image_urls,
                            'category': 'cultural',  # 默认分类
                            'popularity': int(rating * 10) if rating > 0 else 0,  # 根据评分设置热度
                        }
                    )

                    action = '添加' if created else '更新'
                    self.stdout.write(f'{action}: {name} ({len(image_urls)}张图片)')
                    added_count += 1

                    # 控制请求频率
                    time.sleep(0.5)

                page += 1

                # 如果这一页没有获取到新的景点，停止
                if len(pois) < page_size:
                    break

            except Exception as e:
                self.stdout.write(self.style.ERROR(f'处理第{page}页时出错: {str(e)}'))
                break

        self.stdout.write(
            self.style.SUCCESS(f'完成！共添加了 {added_count} 个热门景点')
        )

        # 显示统计信息
        total = Attraction.objects.count()
        with_images = Attraction.objects.filter(
            amap_image_urls__isnull=False
        ).exclude(amap_image_urls=[]).count()

        self.stdout.write(f'当前总景点数: {total}')
        self.stdout.write(f'有图片的景点数: {with_images}')
